<template>
  <div class="third-party-sync">
    <el-table
      ref="multipleTable"
      :data="jobTemplates"
      style="width: 100%"
      highlight-current-row
      @current-change="handleCurrentChange"
      :row-key="getRowKey"
    >
      <!-- 如果需要显示索引 -->
      <el-table-column type="index" label="序号" width="55"></el-table-column>
      <el-table-column prop="id" label="任务ID" width="100"></el-table-column>
      <el-table-column prop="jobDesc" label="任务描述" width="200"></el-table-column>
      <el-table-column prop="projectName" label="所属项目" width="200"></el-table-column>
      <el-table-column prop="jobCron" label="Cron表达式" width="200"></el-table-column>
      <el-table-column label="路由策略">
        <template #default="scope">
          {{ getRouteStrategyLabel(scope.row.executorRouteStrategy) }}
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="updatePagination('size', $event)"
      @current-change="updatePagination('page', $event)"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
  </div>
</template>

<script>
import * as jobTemp from '@/api/datax-job-template'
import * as jobInfo from '@/api/datax-job-info'

export default {
  data() {
    return {
      jobTemplates: [],
      routeStrategies: [
        { value: 'FIRST', label: '第一个' },
        { value: 'LAST', label: '最后一个' },
        { value: 'ROUND', label: '轮询' },
        { value: 'RANDOM', label: '随机' },
        { value: 'CONSISTENT_HASH', label: '一致性HASH' },
        { value: 'LEAST_FREQUENTLY_USED', label: '最不经常使用' },
        { value: 'LEAST_RECENTLY_USED', label: '最近最久未使用' },
        { value: 'FAILOVER', label: '故障转移' },
        { value: 'BUSYOVER', label: '忙碌转移' }
        // { value: 'SHARDING_BROADCAST', label: '分片广播' }
      ],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      selectedRow: null
    }
  },

  created() {
    this.fetchJobTemplates()
  },

  methods: {
    getRouteStrategyLabel(value) {
      const strategy = this.routeStrategies.find(strategy => strategy.value === value)
      return strategy ? strategy.label : (value || '未知')
    },
    updatePagination(type, newValue) {
      if (type === 'size') {
        if (newValue > 0 && newValue !== this.pageSize) {
          this.pageSize = newValue
          this.currentPage = 1
        }
      } else if (type === 'page') {
        if (newValue > 0 && newValue !== this.currentPage) {
          this.currentPage = newValue
        }
      }
      this.fetchJobTemplates()
    },
    handleCurrentChange(currentRow, oldCurrentRow) {
      this.selectedRow = currentRow
    },
    getRowKey(row) {
      return row.id
    },
    fetchJobTemplates() {
      const params = {
        current: this.currentPage,
        size: this.pageSize,
        jobGroup: 0,
        triggerStatus: -1,
        jobDesc: '',
        executorHandler: '',
        userId: 0
      }
      jobTemp.getList(params)
        .then(response => {
          if (response && response.content) {
            const { data = [], recordsTotal = 0 } = response.content
            this.jobTemplates = data
            this.total = recordsTotal
          } else {
            console.error('接口返回数据格式不正确:', response)
          }
        })
        .catch(error => {
          console.error('获取任务模板失败:', error)
        })
    },
    // 添加 createSelectedJob 方法
    createSelectedJob(serializedConfigJson, jobDesc) {
      debugger
      if (this.selectedRow) {
        const jobData = {
          jobJson: serializedConfigJson,
          templateId: this.selectedRow.id,
          executorRouteStrategy: this.selectedRow.executorRouteStrategy,
          executorHandler: 'apiDataSyncJobHandler',
          executorBlockStrategy: this.selectedRow.executorBlockStrategy,
          glueType: 'GLUE_API',
          addTime: new Date().toISOString(),
          updateTime: new Date().toISOString(),
          jobGroup: this.selectedRow.jobGroup,
          projectId: this.selectedRow.projectId,
          projectName: this.selectedRow.projectName,
          jobCron: this.selectedRow.jobCron,
          jobDesc: jobDesc
        }
        jobInfo.createJob(jobData)
          .then(response => {
            debugger
            if (response.code === 200) {
              this.$message.success('任务创建成功')
            } else {
              this.$message.error(response.msg)
            }
          })
          .catch(error => {
            console.error('创建任务失败:', error)
          })
      } else {
        console.error('未选中任何任务模板')
      }
    }
  }
}
</script>

<style scoped lang="scss">
.third-party-sync {
  padding: 20px;
}
</style>
